/**
 * @class   wosh::PersistenceManager
 * @brief   CoreModule providing (de)Serialization functionalities.



 * @ingroup CoreModules
 ****************************************************************************
 * @version 0.8.399 $Id: PersistenceManager.h 2861 2010-08-07 02:42:53Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/*! \page page_core
 * \htmlonly <hr/> \endhtmlonly
 * \section page_core_persistence Persistence
 *
 * The basic task of persistency is simple.
 * The application or some important data of the application is represented
 * as a set of objects with some references to each other. Persistency means,
 * that these objects can be saved to permanent storage i.e. a file and later
 * the program will be able to restore the original state from that file.
 * More precisely an application or data is persistent,
 * if its lifetime is longer than the running time of the application.
 *
 *
 * [..]
 *
 * \see wosh::PersistenceManager
 *
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_Core_PersistenceManager_H__
 #define __WOSH_Core_PersistenceManager_H__

 #include <woshDefs.h>
 #include <core/WoshModule.h>
 #include <core/Serialization.h>
 #include <core/EncoderProtocol.h>
 #include <core/DataModels.h>
 #include <core/Fact.h>


namespace wosh {

 #define _PersistenceDb_KEY_Protocol			"Protocol"
 #define _PersistenceDb_KEY_ProtocolVersion		"ProtocolVersion"
 #define _PersistenceDb_KEY_EncodeCompact		"EncodeCompact"

 #define _PersistenceDb_KEY_FileInput			"FileInput"
 #define _PersistenceDb_KEY_FileOutput			"FileOutput"
 #define _PersistenceDb_KEY_LastLoadTS			"LastLoadTS"
 #define _PersistenceDb_KEY_LastSaveTS			"LastSaveTS"

// template <class T> class DataFieldCollector;

class PersistenceDb : public Object
 {
	WOSH_CLASSNAME(wosh::PersistenceDb)
	WOSH_CLASS_ABSTRACT(true)

	public:
		PersistenceDb();
		virtual ~PersistenceDb();

	public:
		virtual WRESULT save() const = 0;
		virtual WRESULT load() = 0;

/** @name Getters
 * @{
 ******************************************************************************/
	public:
		inline const PropertiesProvider& getProperties() const	{ return Properties; }
		inline PropertiesProvider& getProperties()				{ return Properties; }

		inline std::string getProtocol() const					{ return Properties.getValueOf(_PersistenceDb_KEY_Protocol).toString(); }
		inline double getProtocolVersion() const				{ return Properties.getValueOf(_PersistenceDb_KEY_ProtocolVersion).toDouble(0.0); }
		inline bool isEncodeCompact() const						{ return Properties.getValueOf(_PersistenceDb_KEY_EncodeCompact).toBoolean(true); }

		inline std::string getFileInput() const					{ return Properties.getValueOf(_PersistenceDb_KEY_FileInput).toString(); }
		inline std::string getFileOutput() const				{ return Properties.getValueOf(_PersistenceDb_KEY_FileOutput).toString(); }

		static DataFieldCollector<PersistenceDb>* getDataFields();

//@}
		virtual WRESULT setLog( LogContext& log );

		virtual WRESULT setProtocol( const std::string& protocol, double version = 0.0 );

		virtual WRESULT setEncodeCompact( bool compact_enabled );

		virtual WRESULT setFileInput( const std::string& wosh_path );
		virtual WRESULT setFileOutput( const std::string& wosh_path );

	//	WRESULT setDataAdapter( IDataAdapter* adapter ) {
	//		this->dataAdapter = adapter;
	//		return WRET_OK;
	//	 }

	protected:
		// protocol reference
		// output settings
		// binding with container (using DataModel!!?!!)

		PropertiesProvider Properties;
		LogContext* log;
	//	IDataAdapter* dataAdapter;

}; // class def

//-----------------------------------------------------------------------------

 #define _PersistenceManager_NAME							"PersistenceManager"
 #define _PersistenceManager_URI							":Persistence"

 #define _PersistenceManager_KEY_Encoders_Count				"EncoderCount"

 #define _PersistenceManager_KEY_AutoLoadProtocols			"AutoLoadProtocols"
 
 #define _PersistenceManager_METHOD_LoadProtocol			"load_protocol"
 #define _PersistenceManager_METHOD_Protocols_list			"list_protocols"
 #define _PersistenceManager_METHOD_DataBases_list			"list_db"

 #define _PersistenceManager_METHOD_ListSupportedProtocols	"list_supported"

 #define _PersistenceManager_EVENT_ProtocolUpdated			"ProtocolUpdated"


class WoshKernel;

class PersistenceManager :	public WoshModule,
							public IEncoderProtocolListener
 {
	WOSH_MODULE(wosh::PersistenceManager)

	typedef ListT<EncoderProtocol*> tEncoderProtocolList;
	typedef ListT<PersistenceDb*> tPersistenceDbList;



	protected:
		PersistenceManager( const WoshKernel* parent = NULL );

		WRESULT onKernelInitializing();

		WRESULT onKernelStopped();

		friend class wosh::WoshKernel;

	public:
		virtual ~PersistenceManager();


	public:
		WRESULT installProtocol( EncoderProtocol* encoder_protocol, bool raise_event );
		EncoderProtocol* loadProtocol( const std::string& encoder_protocol, double version = 0.0 );


	public:
		static int getEncoderProtocolsFor( std::vector<std::string>& encoder_protocols, const char* classname, double version = 0.0 );

		static int64 serializeTo( const ISerializable* object, const char* protocol, char* buffer, int64 buffer_size, int encoder_options );
		static int64 deserializeFrom( ISerializable* object, const char* protocol, const char* buffer, int64 buffer_size );

		static WRESULT serializeTo( const PersistenceDb* object );


	public:
		static PersistenceDb* createDb( const char* protocol_name, double protocol_version = 0.0 );


//BOH:
	public:
		template <class T>
		static WRESULT loadObjects( std::vector<T*>& objects, const char* protocol_name, const std::string& params, double protocol_version = 0.0 ) {
			if ( getInstance() == NULL ) return WRET_ERR_ILLEGAL_USE;
			getInstance()->Protocols.transactionBeginRead();
			EncoderProtocol* encoder_protocol = getInstance()->getProtocol_(protocol_name, protocol_version);
			if ( encoder_protocol == NULL ) {
				getInstance()->Protocols.transactionEnd();
				return WRET_ERR_PARAM;
			 }
			WRESULT ret = WRET_OK;
			std::vector<ISerializable*> objects_s;
			ret = encoder_protocol->loadObjects(objects_s, params);
			std::vector<ISerializable*>::const_iterator it;
			const std::vector<ISerializable*>::const_iterator it_end = objects_s.end();
			for ( it=objects_s.begin(); it!=it_end; ++it ) {
				//if ( *it == NULL ) continue;
				objects.push_back( dynamic_cast<T*>(*it) );
			 }
			getInstance()->Protocols.transactionEnd();
			return ret;
		 }

		template <class T>
		static WRESULT saveObjects( const std::vector<T*>& dataset, const char* protocol_name, const std::string& params, double protocol_version = 0.0 ) {
			if ( getInstance() == NULL ) return WRET_ERR_ILLEGAL_USE;
			getInstance()->Protocols.transactionBeginRead();
			EncoderProtocol* encoder_protocol = getInstance()->getProtocol_(protocol_name, protocol_version);
			if ( encoder_protocol == NULL ) {
				getInstance()->Protocols.transactionEnd();
				return WRET_ERR_PARAM;
			 }
			WRESULT ret = WRET_OK;
			std::vector<ISerializable*> objects;
			typename std::vector<T*>::const_iterator it;
			const typename std::vector<T*>::const_iterator it_end = dataset.end();
			for ( it=dataset.begin(); it!=it_end; ++it ) {
				if ( *it == NULL ) continue;
				objects.push_back( *it );
			 }
			ret = encoder_protocol->saveObjects(objects, params);
			getInstance()->Protocols.transactionEnd();
			return ret;
		 }

		template <class Key, class Value>
		static WRESULT saveObjects( const std::map<Key, Value*>& dataset, const char* protocol_name, const std::string& params, double protocol_version = 0.0 ) {
			if ( getInstance() == NULL ) return WRET_ERR_ILLEGAL_USE;
			getInstance()->Protocols.transactionBeginRead();
			EncoderProtocol* encoder_protocol = getInstance()->getProtocol_(protocol_name, protocol_version);
			if ( encoder_protocol == NULL ) {
				getInstance()->Protocols.transactionEnd();
				return WRET_ERR_PARAM;
			 }
			WRESULT ret = WRET_OK;
			std::vector<ISerializable*> objects;
			typename std::map<Key, Value*>::const_iterator it;
			const typename std::map<Key, Value*>::const_iterator it_end = dataset.end();
			for ( it=dataset.begin(); it!=it_end; ++it ) {
				if ( it->second == NULL ) continue;
				objects.push_back( it->second );
			 }
			ret = encoder_protocol->saveObjects(objects, params);
			getInstance()->Protocols.transactionEnd();
			return ret;
		 }


//@}
/** @name Message Events (incoming message)
 * @{
 ******************************************************************************/
	public:
		void busMessage( const Message& message, const Bus* source );
//@}
/** @name EncoderProtocol Events
 * @{
 ******************************************************************************/
	protected:
		void encoder_protocol_db_action( const std::string& db_name, EncoderProtocol* source );
//@}
/** @name PersistenceDb Events
 * @{
 ******************************************************************************/
	protected:
		void persistence_db_action( int state, PersistenceDb* source );
//@}

	private:
		/**
		 * @brief  Access the PersistenceManager singleton. Gamma Pattern.
		 *         Static reference is allocated and detroyed by WoshKernel on constructor/destructor respectively
		 * @return pointer to PersistenceManager singleton. May be NULL (if kernel has not been allocated yet)
		 */
		static PersistenceManager* getInstance();

		friend class wosh::EncoderProtocol;
		friend class wosh::PersistenceDb;

		static EncoderProtocol* getProtocolByType_( const char* class_name );

		static EncoderProtocol* getProtocol_(const char* protocol_name,  double protocol_version = 0.0, bool strict = false );

	private:
		Response* mmDoList( const Request* request );
		Response* mmDoListSupportedProtocols( const Request* request );
		Response* mmDoLoadProtocol( const Message* requestMessage );

	protected:
		tEncoderProtocolList Protocols;
		URI ProtocolsVirtualURI;			///< base URI for Encoders (:/Persistence/Protocols)

		tPersistenceDbList DataBases;
		URI DataBasesVirtualURI;			///< base URI for DataBases (:/Persistence/DB)

}; // class def


//-----------------------------------------------------------------------------

template <class OBJECT_TYPE>
class PersistenceDbGeneric : public PersistenceDb
 {
	WOSH_CLASSNAME(wosh::PersistenceDbGeneric)
	WOSH_CLASS_ABSTRACT(false)

	public:
		PersistenceDbGeneric()
			: PersistenceDb(), adapter(NULL) {
				
		 }
		virtual ~PersistenceDbGeneric() {
			setAdapter(NULL);
		 }

	public:
		virtual WRESULT save() const {
			if ( this->adapter == NULL ) {
				return WRET_ERR_PARAM;
			 }
			this->adapter->transactionBeginRead();
			//unsigned int count = 
				this->adapter->loadItems();
			WRESULT ret = PersistenceManager::saveObjects( this->adapter->getItems(), getProtocol().c_str(), getFileOutput() );

			this->adapter->transactionEnd();
			return ret;
		 }

		virtual WRESULT load() {
			return WRET_OK;
		 }

		inline DataAdapter<OBJECT_TYPE>* getAdapter() { return this->adapter; }

		void setAdapter( DataAdapter<OBJECT_TYPE>* data_adapter ) {
			if ( this->adapter != NULL )
				delete this->adapter;
			this->adapter = data_adapter;
		 }


	protected:
		DataAdapter<OBJECT_TYPE>* adapter;


}; // class def


/**
 * @class   wosh::PersistenceManager_ProtocolUpdated
 * @brief   Raised when a protocol is added or updated.
 *
 * Internally, data is stored as wosh::List. Supports also wosh::Variant type.
 *
 * Fields are:
 *  - \c protocol name [Variant::STRING] (always present, first item of the list)
 *  - \c action type (optional, default: new installed protocol)
 *
 * Some getters are provided for convenience:
 * \code

 * \endcode
 *
 * @see     wosh::Fact
 * @see     wosh::UserManager
 ****************************************************************************
 * @version 0.8.399 $Id: PersistenceManager.h 2861 2010-08-07 02:42:53Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
class PersistenceManager_ProtocolUpdated : public Fact
 {
	WOSH_SERIALIZABLE(wosh::PersistenceManager_ProtocolUpdated)

	public:
		/**
		 * @brief  Empty constructor.
		 */
		PersistenceManager_ProtocolUpdated()
			: Fact(_PersistenceManager_EVENT_ProtocolUpdated) { }
		/**
		 * @brief  Constructor with initializers.
		 * @param protocol [in] name of the (updated) user
		 */
		PersistenceManager_ProtocolUpdated( const std::string& protocol );
		/**
		 * @brief  Constructor with initializers.
		 * @param protocol [in] name of the (updated) user
		 * @param protocol_action [in] update type: 1=new_protocol
		 */
		PersistenceManager_ProtocolUpdated( const std::string& protocol, short protocol_action = 1 );
		/**
		 * @brief  Copy constructor.
		 * @param m [in] the source object to be copied
		 */
		PersistenceManager_ProtocolUpdated( const PersistenceManager_ProtocolUpdated& m )
			: Fact(m) { }
		/**
		 * @brief  Empty destructor.
		 */
		virtual ~PersistenceManager_ProtocolUpdated() { }

	public:
		/**
		 * @brief   Get name of the (updated) protocol
		 * @return  protocol as string
		 */
		std::string getProtocolName() const;

		short getProtocolAction() const;

		inline bool isProtocolNew() const				{ return (getProtocolAction() == 1); }
		inline bool isProtocolRemoved() const			{ return (getProtocolAction() == 2); }

}; // class def


}; // namespace wosh

#endif //__WOSH_Core_PersistenceManager_H__
